package com.diandiansong.app.ui.index;

import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.diandiansong.app.R;
import com.diandiansong.app.entity.CityInfo;
import com.diandiansong.app.entity.IndexInfo;
import com.diandiansong.app.event.KILL_REFRESH;
import com.diandiansong.app.event.NEWS;
import com.diandiansong.app.event.SECOND;
import com.diandiansong.app.ui.Search;
import com.diandiansong.app.ui.commonlist.CommonList;
import com.diandiansong.app.ui.commonlist.KillList;
import com.diandiansong.app.utils.A;
import com.diandiansong.app.utils.Api;
import com.diandiansong.app.widgets.SearchView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import diandiansong.library.ui.base.BaseAct;
import diandiansong.library.ui.base.BaseFrag;
import diandiansong.library.utils.CCallBack;
import diandiansong.library.utils.DensityUtils;
import diandiansong.library.utils.ImgLoader;

/**
 * 首页-主页
 */
public class IndexMain extends BaseFrag {

    @BindView(R.id.banner)
    Banner mBanner;
    Unbinder unbinder;
    @BindView(R.id.search_view)
    SearchView mSearchView;
    @BindView(R.id.tv_a_news)
    TextView mTvANews;
    @BindView(R.id.ll_kill_contaner)
    LinearLayout mLlKillContaner;
    @BindView(R.id.ll_kill)
    LinearLayout mLlKill;
    @BindView(R.id.tv_kh)
    TextView mTvKillH;
    @BindView(R.id.tv_km)
    TextView mTvKillM;
    @BindView(R.id.tv_ks)
    TextView mTvKillS;
    @BindViews({R.id.go_index_cate1, R.id.go_index_cate2, R.id.go_index_cate3})
    ImageView[] mGoIndexCate;
    @BindView(R.id.tv_city_name)
    TextView mTvCityName;
    @BindView(R.id.ll_today)
    LinearLayout mLlToday;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        if (mScreenWidth == -1) {
            Display mDisplay = getActivity().getWindowManager().getDefaultDisplay();
            mScreenWidth = mDisplay.getWidth();
        }

        View view = inflater.inflate(R.layout.index_main, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initApi();
    }

    public static int mKillRemainTime;
    public static String mKillEndTime;

    private void initApi() {
        ((BaseAct) getActivity()).onLoading();
        initIndexData();


        A.city(null, new CCallBack<CityInfo>() {
            @Override
            public void onSuccess(CityInfo o) throws Exception {
                CityInfo.saveCityInfo(getActivity(), o);
            }

            @Override
            public void onFailure(int code, String msg) {
                toast(msg);
                onLoaded();
            }
        });

    }

//    public static CommodityKillInfo sCommodityKillInfo;

    private void refreshKillData() {
        A.index(new CCallBack<IndexInfo>() {
            @Override
            public void onSuccess(IndexInfo o) throws Exception {
                handleKill(o);
            }


            @Override
            public void onFailure(int code, String msg) {
                if (mLlKill != null) {
                    mLlKill.setVisibility(View.GONE);
                }
            }
        });
    }

    private void handleKill(IndexInfo o) {
        IndexInfo.Data data = o.getData();

        boolean enableKill = data.isEnableKill();
        if (!enableKill) {
            mLlKill.setVisibility(View.GONE);
            return;
        }


        //剩余时间
        try {
            String killTime = data.getKillTime();
            mKillRemainTime = Integer.valueOf(killTime);
            mKillEndTime = data.getKillEndTime();
        } catch (Exception e) {
            e.printStackTrace();
        }

        mLlKillContaner.removeAllViews();
        List<IndexInfo.Data.KillInfo> listInfo = data.getKillInfo();
        for (int i = 0; i < listInfo.size(); i++) {
            IndexInfo.Data.KillInfo item = listInfo.get(i);
            View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.index_kill_item, null);

            TextView n = itemView.findViewById(R.id.tv_name);
            TextView p = itemView.findViewById(R.id.tv_price);
            TextView op = itemView.findViewById(R.id.tv_oprice);
            TextView d = itemView.findViewById(R.id.tv_des);
            ImageView l = itemView.findViewById(R.id.iv_logo);

            n.setText(item.getCommodityName());
            d.setText(item.getSpecInfo());


            String unit = item.getUnit();
            if (unit == null || unit.isEmpty() || unit.equals("/")) {
                unit = "";
            } else {
                unit = "/" + unit;
            }

            p.setText("￥" + item.getKillPrice() + unit);
            op.setPaintFlags(op.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
            op.setText("￥" + item.getPrice() + unit);


            ImgLoader.display(l, item.getImgs());

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    KillList.start(getActivity());
                }
            });

            mLlKillContaner.addView(itemView);
        }
    }

    List<IndexInfo.Data.Article> mArticles;
    int mScreenWidth = -1;

    private void initIndexData() {


        A.index(new CCallBack<IndexInfo>() {
            @Override
            public void onSuccess(IndexInfo o) throws Exception {
                ((BaseAct) getActivity()).onLoaded();

                mTvCityName.setText(o.getData().getCityName());

                handleKill(o);

                //banner
                try {
                    List<IndexInfo.Data.Banner> banner = o.getData().getBanner();
                    if (banner != null) {
                        initBannner(banner);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //大分类
                List<IndexInfo.Data.ThreeInfo> threeInfo = o.getData().getThreeInfo();
                if (threeInfo != null) {
                    for (int i = 0; i < threeInfo.size(); i++) {
                        if (i < 3) {
                            final IndexInfo.Data.ThreeInfo item = threeInfo.get(i);
                            ImgLoader.display(mGoIndexCate[i], item.getImgs());
                            mGoIndexCate[i].setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    BigCate.start(getActivity(), item.getTitle(), item.getModel());
                                }
                            });
                        }
                    }
                }

                //文章
                try {
                    mArticles = o.getData().getArticle();
                    mTvANews.setText(mArticles.get(0).getTitle());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //今日推荐
                List<IndexInfo.Data.TjInfo> tjInfo = o.getData().getTjInfo();
                mLlToday.removeAllViews();
                for (int i = 0; i < tjInfo.size(); i = i + 2) {
                    View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.index_recomend_item, null);

                    int i1 = (int) ((mScreenWidth - DensityUtils.dp2px(getActivity(), 20)) / 2 / 1.35);

                    Log.e("wit", "x" + i1);

                    {
                        View lll = itemView.findViewById(R.id.ll_l);
                        TextView nl = itemView.findViewById(R.id.tv_name_l);
                        TextView dl = itemView.findViewById(R.id.tv_des_l);
                        TextView pl = itemView.findViewById(R.id.tv_price_l);
                        //间距8+4+8
                        ImageView il = itemView.findViewById(R.id.iv_logo_l);
                        il.getLayoutParams().height = i1;

                        {
                            final IndexInfo.Data.TjInfo item = tjInfo.get(i);
                            ImgLoader.display(il, item.getImgs());
                            nl.setText(item.getCommodityName());
                            dl.setText(item.getSpecInfo());
                            pl.setText("￥" + item.getPrice() + item.getUnit());

                            lll.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    GoodDetail.start(getActivity(), item.getCommodityId());
                                }
                            });
                        }
                    }

                    {
                        View llr = itemView.findViewById(R.id.ll_r);
                        TextView nl = itemView.findViewById(R.id.tv_name_r);
                        TextView dl = itemView.findViewById(R.id.tv_des_r);
                        TextView pl = itemView.findViewById(R.id.tv_price_r);
                        ImageView il = itemView.findViewById(R.id.iv_logo_r);
                        il.getLayoutParams().height = i1;

                        if (i + 1 < tjInfo.size()) {
                            {
                                final IndexInfo.Data.TjInfo item = tjInfo.get(i + 1);
                                ImgLoader.display(il, item.getImgs());
                                nl.setText(item.getCommodityName());
                                dl.setText(item.getSpecInfo());
                                pl.setText("￥" + item.getPrice() + item.getUnit());

                                llr.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        GoodDetail.start(getActivity(), item.getCommodityId());
                                    }
                                });
                            }

                        } else {
                            llr.setVisibility(View.INVISIBLE);
                        }
                    }
                    mLlToday.addView(itemView);
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                toast(msg);
                onLoaded();
            }
        });

    }

    private void initBannner(final List<IndexInfo.Data.Banner> banner) {
        //设置banner样式
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        mBanner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                ImgLoader.display(imageView, (String) path);
            }
        });
        //设置图片集合
        mBanner.setImages(new ArrayList<String>() {
            {
                for (IndexInfo.Data.Banner item : banner) {
                    add(item.getImgUrl());
                }
            }
        });
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                String linkUrl = banner.get(position).getLinkUrl();
                Web.start(getActivity(), linkUrl);
            }
        });
        //设置banner动画效果
        mBanner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        mBanner.isAutoPlay(true);
        //设置轮播时间
        mBanner.setDelayTime(3500);
        //设置指示器位置（当banner模式中有指示器时）
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        mBanner.start();

        mSearchView.setCusOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Search.start(getActivity());
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.go_news_list)
    public void onViewClicked() {
        NewsList.start(getActivity());
    }

    @OnClick(R.id.go_best_selling)
    public void onMGoBestSellingClicked() {
        BestSelling.start(getActivity());
    }

    @OnClick(R.id.go_use_list)
    public void onMGoUseListClicked() {
        CommonList.start(getActivity());
    }

    @OnClick(R.id.go_favorite)
    public void onMGoFavoriteClicked() {
        Favorite.start(getActivity());
    }

    @OnClick(R.id.go_order)
    public void onMGoOrderClicked() {
        Order.start(getActivity());
    }

    @OnClick(R.id.go_msg)
    public void onMGoMsgClicked() {
        MsgList.start(getActivity());
    }

    public static class Refresh {
    }

    public static void doRefresh() {
        EventBus.getDefault().post(new Refresh());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(Refresh refresh) {
        initIndexData();
    }


    public static String secToTime(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0)
            return "00:00:00";
        else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr = "00:" + unitFormat(minute) + ":" + unitFormat(second);
            } else {
                hour = minute / 60;
//                if (hour > 99)
//                    return "99:59:59";
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
            }
        }
        return timeStr;
    }

    public static String unitFormat(int i) {
        String retStr = null;
        if (i >= 0 && i < 10)
            retStr = "0" + Integer.toString(i);
        else
            retStr = "" + i;
        return retStr;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void reciveSecond(SECOND s) {
        if (mTvKillH == null || mTvKillM == null || mTvKillS == null || mKillRemainTime < 1) {
            return;
        }
        mKillRemainTime--;
        String ts = secToTime(mKillRemainTime);
        String[] tss = ts.split(":");
        mTvKillH.setText(tss[0]);
        mTvKillM.setText(tss[1]);
        mTvKillS.setText(tss[2]);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void reciveKillRefresh(KILL_REFRESH s) {
        refreshKillData();
    }

    int ArticlesRefreshCount;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void reciveNews(NEWS s) {
        ArticlesRefreshCount++;
        if (mTvANews != null && mArticles != null && mArticles.size() > 0) {
            final IndexInfo.Data.Article article = mArticles.get(ArticlesRefreshCount % mArticles.size());
            mTvANews.setText(article.getTitle());
            mTvANews.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Web.start(getActivity(), Api.URL + "/app/news_view?id=" + article.getId());
                }
            });
        }
    }
}
